/*
 * Copyright 2011 www.pretty-tools.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    var response = {"request": request};
    try
    {
        if (request.call) // need to call method
        {
            var method = request.call;
            var idx = method.indexOf('.');

            if (idx == -1) // simple method call
                response.returnedValue = window[method].apply(null, request.args);
            else // call method of object
            {
                var object = method.substring(0, idx);
                method = method.substring(idx + 1);

                var obj = window[object];
                response.returnedValue = obj[method].apply(obj, request.args);
            }
        }
        else if (request.clone) // need to get/clone some object
        {
            var originalObject = window[request.clone];
            if (originalObject["clone"]) // object has clone() method
                response.value = originalObject.clone();
            else
                response.value = originalObject;
        }
        else if (request.create) // need to create new object
        {
            var objectConstructor = window[request.create];
            var wrapper = function() {
                objectConstructor.apply(this, arguments);
            };
            wrapper.prototype = objectConstructor.prototype;
            response.value = new wrapper(request.args);
        }
        else
        {
            throw "Invalid request";
        }
    }
    catch(e)
    {
        console.log(e);

        response.exception = e;
    }

    try {
        sendResponse(response);
    } catch(ex) {
        console.log(ex);
    }
});
